package me.yxy.mobanddd.domain.shipment;

import com.google.common.collect.Iterables;
import me.yxy.mobanddd.domain.transportorder.TransportOrder;
import me.yxy.mobanddd.domain.transportorder.TransportOrderRepository;
import me.yxy.mobanddd.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 调度单工厂，负责创建调度单
 */
@Component
public class ShipmentFactory {


    @Autowired
    private ShipmentRepository shipmentRepository;

    @Autowired
    private TransportOrderRepository transportOrderRepository;


    /**
     * 根据初始运单来创建一个调度单
     * @param transportOrderIds
     * @return
     */
    public Shipment createWithTransportOrders(List<Long> transportOrderIds) {

        //首先要确保这些运单都没有被加入到全天的调度单中
        Iterable<TransportOrder> orderOptions = transportOrderRepository.findAllById(transportOrderIds);
        checkOrderOptions(orderOptions,transportOrderIds);

        Shipment shipment =  initEmptyShipmentDto();
        for (TransportOrder order : orderOptions) {
            order.setShipment(shipment);
        }

        //TODO 思考，这个时候，调度单会和运单有一对多的关系，在DomainEntity中，是否需要持有一个List<TransportOrder>呢？ 看情况吧，如果确实特别需要，则增加

        return shipment;
    }

    private Shipment initEmptyShipmentDto() {
        Shipment shipment = new Shipment();
        shipment.setStatus(ShipmentStatus.INIT);
        shipment.setType(1);
        shipmentRepository.save(shipment);
        return shipment;
    }


    private void checkOrderOptions(Iterable<TransportOrder> orderOptions, List<Long> orderIds) {
        int size =  Iterables.size(orderOptions);
        if(size!=orderIds.size()){
            throw new BusinessException("所选调度单参数不正确");
        }

        for (TransportOrder order : orderOptions) {
            if(order.getShipment()!=null){
                throw new BusinessException("运单"+order.getId()+"已经被添加到其他调度单中","有运单已经被添加到其他调度单中，操作失败");
            }
        }
    }


}
